package com.mmall.concurrency.example.concurrent;

import com.mmall.concurrency.annoations.ThreadSafe;
import com.mmall.concurrency.example.atomic.AtomicExample3;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Slf4j
@ThreadSafe
public class ConcurrentSkipListMapExample {

	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);
   // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static Map<Integer, Integer> map = new ConcurrentSkipListMap<>();

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int count = i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    update(count); // 这里为什么需要final类型的值？
                    semaphore.release();
                }catch (Exception e){
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await(); // 阻塞main线程，直到所有的线程都执行并完成计数
        executorService.shutdown();
        log.info("size:{}", map.size());
    }
    //
    private static void update(int i) {
        map.put(i, i);
    }
}
